package com.diorsunion.hedge.util;

import java.lang.reflect.Field;

/**
 * Created by harley-dog<custer7572@163.com> on 15/12/15.
 */
public class ReflectionUtil {
    public static void setValue(Object obj, String fieldName, Object value) throws IllegalAccessException {
        Class c = obj.getClass();
        Field field = getField(obj,fieldName);
        if (field != null) {
            field.setAccessible(true);
            field.set(obj, value);
        }
    }

    public static Field getField(Object obj, String fieldName) throws IllegalAccessException {
        Class c = obj.getClass();
        Field field = null;
        while (true) {
            if (c == null) {
                break;
            }
            try {
                field = c.getDeclaredField(fieldName);
                break;
            } catch (NoSuchFieldException e) {
                c = c.getSuperclass();
            }
        }
        if (field != null) {
            field.setAccessible(true);
            return field;
        }
        return null;
    }
}
